package com.bfsuol.bfsuolframework.core.controller;

import com.bfsuol.bfsuolframework.core.controller.json.MessageJson;
import com.bfsuol.bfsuolframework.core.controller.support.Pagination;
import com.bfsuol.bfsuolframework.core.controller.support.QueryParam;
import com.bfsuol.bfsuolframework.core.entity.Entity;
import com.bfsuol.bfsuolframework.core.service.Service;
import com.bfsuol.bfsuolframework.core.spring.QueryParameter;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

public abstract class CRUDControllerSupport<E extends Entity> extends SpringControllerSupport implements SpringController {

	public abstract Service<E> getService();
	
	@RequestMapping("/index")
	public String index(Model model){
		return getViewNamedPath("index");
	}
	
	@RequestMapping("/list")
	public String list(
			@QueryParameter("query") QueryParam query,
			@ModelAttribute("page") Pagination page){
		
		page = getService().getPage(query, page);
		
		return getViewNamedPath("list");
	}
	
	@RequestMapping("/input")
	public String create(@ModelAttribute E entity,Model model){
		return getViewNamedPath("input");
	}
	
	@RequestMapping("/input/{id}")
	public String edit(@PathVariable("id") Long id, Model model){
		E entity = getService().getById(id);
		model.addAttribute(entity);
		return getViewNamedPath("input");
	}
	
	@RequestMapping("/save")
	public @ResponseBody MessageJson save(@ModelAttribute E entity){
		if(entity.isNew()){
			getService().save(entity);
		}else{
			getService().update(entity);
		}
		return MessageJson.information("保存成功");
	}
	
	
	@RequestMapping("/delete/{id}")
	public @ResponseBody MessageJson delete(@PathVariable("id") Long id){
		getService().delete(id);
		return MessageJson.information("成功删除1条");
	}
	
	@RequestMapping("/delete")
	public @ResponseBody MessageJson delete(@RequestParam("ids") Long[] ids){
		if(ids == null || ids.length == 0){
			return MessageJson.error("没有删除");
		}
		for(Long id : ids){
			getService().delete(id);
		}
		return MessageJson.information("成功删除"+ids.length+"条");
	}
}
